<?php
namespace app\admin\controller;
use app\base\Controller;
/**
* 
*/
class Nodes extends Controller
{
    
    public function __construct(){
        parent::__construct();
        $this->onode = new \app\admin\model\AdminNodes();
    }

    public function index(){
        $node_list = $this->onode->node_list();
        $pt_nodes = $this->onode->where(['parent_id'=>'0','disable'=>'false','is_use'=>'true'])->select(); 
        //$pt_nodes = $pt_nodes->toArray();
        $this->assign('ptnodes',$pt_nodes);
        $this->assign('nodelist',$node_list);
        return $this->view->fetch();
    }

    public function get_node(){
        $node_id = $this->post('nodeid');
        $node = $this->onode->where(['node_id'=>$node_id,'disable'=>'false'])->find();
        if(!empty($node)){
            $node = $node->toArray();
        }
        return ajax_return($node);
    }

    public function post($name){
        $tmp_name = $this->request->post($name);
        if(is_array($tmp_name)){
            foreach ($tmp_name as &$value) {
                $value = htmlspecialchars($value);
            }
            return $tmp_name;
        }else{
            return htmlspecialchars($tmp_name);
        }
    }
    
    public function add_node(){
        $node = $this->request->post()['node'];
        //echo "<pre>";print_r($node);exit;
        $now_time = time();
        $star_node = [
            'name'        => $node['name'],
            'link'        => $node['link'],
            'parent_id'   => is_numeric($node['parent'])?$node['parent']:'1',
            'icon'        => $node['icon'],
            'is_use'      => $node['is_use'],
            'last_modify' => $now_time,
            'order'       => is_numeric($node['order'])?$node['order']:'1',
        ];
        if(isset($node['id'])&&!empty($node['id'])){
            $star_node['node_id'] = $node['id'];
            $status = $this->onode->update($star_node);
        }else{
            $star_node['create_time'] = $now_time;
            $star_node['auth'] = random_code(8,false,true);
            $status = $this->onode->insert($star_node);
        }
        if($status){
            return ajax_return([]);
        }else{
            return ajax_return([],'保存失败','error',1);
        }
    }

    public function del_node(){
        $node_id = $this->post('nodeid');
        $status = $this->onode->where(['node_id'=>$node_id])->delete();
        if($status){
            return ajax_return([]);
        }else{
            return ajax_return([],'删除失败','error',1);
        }
    }
}